import { ajaxPost, ajaxPostFormData } from 'api/axios'
import { HttpUrl, ERR_OK } from 'api/config'
import { removeObjUndefined } from 'common/js/utils'

const actions = {
  GET_VIEW ({ commit }, { module, ...params }) {
    return new Promise(async (resolve) => {
      const url = `${HttpUrl}${module}`

      const res = await ajaxPost(url, {
        ...params
      })

      if (res.code === ERR_OK && res.data) {
        resolve(res.data)
      } else {
        resolve(false)
      }
    })
  },
  SUBMIT_FORM ({ commit }, { listUrl, data }) {
    return new Promise(async (resolve) => {
      const url = `${HttpUrl}${listUrl}`

      const res = await ajaxPost(url, {
        ...removeObjUndefined({ data })
      })

      if (res.code === ERR_OK) {
        SuccessMesaage('操作成功')
        resolve(res.data || true)
      } else {
        ErrorMessage(res.msg || '操作失败')
        resolve(false)
      }
    })
  },
  SUBMIT_DEL ({ commit }, { module, ifFormData = true, ...params }) {
    return new Promise(async (resolve) => {
      const url = `${HttpUrl}${module}`

      let res = {}
      const data = {
        ...removeObjUndefined({ data: params })
      }

      if (ifFormData) {
        res = await ajaxPostFormData(url, data)
      } else {
        res = await ajaxPost(url, data)
      }

      if (res.code === ERR_OK) {
        SuccessMesaage('操作成功')
        resolve(res.data || true)
      } else {
        ErrorMessage(res.msg || '操作失败')
        resolve(false)
      }
    })
  }
}

export default actions
